package cn.edu.lcu.cs.javalearning.net;


import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Mine extends Thread {
    private int amount;
    private ServerSocket serverSocket;

    public Mine() throws IOException {
        this.serverSocket = new ServerSocket(9000);
    }

    @Override
    public void run() {
        try (Socket client = serverSocket.accept();
             ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream())) {
            while (true) {
                Ore ore = dig();
                System.out.println(ore);
                out.writeObject(ore);
                doze();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doze() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private Ore dig() {
        double size = new Random().nextDouble() * 5;
        return new Ore(amount++, size);
    }

    public static void main(String[] args) throws IOException {
        new Mine().start();
    }
}
